package com.superhelper.task.job.stat;

import java.util.Date;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.superhelper.common.utils.DateTimeUtil;
import com.superhelper.common.utils.JsonHelper;
import com.superhelper.task.job.ShopCache;

public abstract class AbstractDailyJob {

    private static int AHEAD_HOURS = 6;
    @Autowired
    protected ShopCache shopCache;

    public DateInfo calJobDate(String jobParam, int preDay) {
        DateInfo di = new DateInfo();
        if (StringUtils.isNotBlank(jobParam)) {
            @SuppressWarnings("unchecked")
            Map<String, Object> map = (Map<String, Object>) JsonHelper.fromJson(jobParam, Map.class);
            if (map.containsKey("startDate")) {
                di.startDate = DateTimeUtil.parseDate((String) map.get("startDate"));
            }
            if (map.containsKey("endDate")) {
                di.endDate = DateTimeUtil.parseDate((String) map.get("endDate"));
            }
        }
        if (di.startDate == null) {
            Date curDate = new Date();
            curDate = preDay == 0 ? curDate : DateTimeUtil.addNDays(curDate, preDay);
            di.startDate = DateTimeUtil.getDate(DateTimeUtil.addNHours(curDate, -AHEAD_HOURS));
            di.endDate = DateTimeUtil.addNDays(di.startDate, 1);
        }
        if (di.endDate == null) {
            di.endDate = DateTimeUtil.addNDays(di.startDate, 1);
        }
        // 考虑到实际情况，从每天6:00到第二天6:00算一个周期天
        di.startDate = DateTimeUtil.addNHours(di.startDate, AHEAD_HOURS);
        di.endDate = DateTimeUtil.addNHours(di.endDate, AHEAD_HOURS);
        di.statDate = DateTimeUtil.getDate(di.startDate);
        return di;
    }

    protected class DateInfo {
        Date startDate;
        Date endDate;
        Date statDate;
    }
}
